package db

import (
	"fmt"
	"frontend-server/global"
	model "frontend-server/model/gv_im"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var ImDB *gorm.DB

func InitDB() {
	imDSN := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=%s&loc=%s",
		global.App.Config.Mysql.MysqlIM.UserName,
		global.App.Config.Mysql.MysqlIM.Passowrd,
		global.App.Config.Mysql.MysqlIM.Host,
		global.App.Config.Mysql.MysqlIM.Port,
		global.App.Config.Mysql.MysqlIM.Database,
		global.App.Config.Mysql.MysqlIM.Charset,
		global.App.Config.Mysql.MysqlIM.ParseTime,
		global.App.Config.Mysql.MysqlIM.Loc,
	)
	imdb, erri := gorm.Open(mysql.Open(imDSN), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if erri != nil {
		panic(fmt.Sprintf("初始化数据库连接失败: %s", erri))
	}
	ImDB = imdb
	ImDB.AutoMigrate(
		&model.GvImUser{},
		&model.GvImRoom{},
		&model.GvImUserRoom{},
		&model.GvImMessage{},
	)
}

func GetImDB() *gorm.DB {
	return ImDB
}
